﻿<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

if (defined('__ROOT__')) {
    define('__ROOT__', dirname(dirname(__FILE__)));
}

/**
 * TMT_Controller
 * @author: Marco Dennstädt
 * @ToDo: Better Role/Team Management
 *
 * Core-Library of TMT, Checks for Login, fetches teams and role.
 * 	Encapsulates logincheck and standard style of the page (navigation, sidebar, header)
 *
 */
class TMT_Controller extends CI_Controller {

    protected $employee;
    protected $active_team;
    private $layout_view = 'template';
    private $content_view = '';
    protected $view_data = array();
    protected $show_sidebar = TRUE;
    protected $headline;

    public function __construct() {
        parent::__construct();

        // Datums-Ausgabe auf Deutsch umstellen
        if ( PHP_OS == "WIN32" || PHP_OS == "WINNT" ) {
            setlocale( LC_ALL, "German_Germany" ); // Windows
        } else {
            setlocale( LC_ALL, "de_DE" ); // Linux
        }
        
        // Installscript
        if (!file_exists('application/config/install.php'))
            redirect('/install');

        $this->benchmark->mark('bench_start');

        //Tank-Auth 
        $this->load->library('tank_auth');


        //$this->load->model('auth/user_roles');


        $this->teams = NULL;
        if (!$this->tank_auth->is_logged_in()) {

            switch ($this->router->class) {
                case 'auth':
                    switch ($this->router->method) {
                        case 'login':break;
                        case 'check_login': break;
                        default: redirect('auth/login/');
                            break;
                    }
                    break;
                case 'survey':
                    break;
                default:
                    redirect('auth/login/');
                    break;
            }
        } else {
            $email = $this->tank_auth->get_email();
            $this->employee = Model\Contactdata::limit(1)->find_by_email($email, FALSE)->employee();
            if (!isset($this->employee))
                $this->tank_auth->logout();

            $this->active_team = 0;
        }

        $this->load->helper('form');
        $this->lang->load('tank_auth');
    }

    protected function set_layout_view($view) {
        $this->layout_view = $view;
    }

    protected function get_layout_view() {
        return $this->layout_view;
    }

    protected function get_content_view() {
        return $this->content_view;
    }

    protected function set_content_view($view) {
        $this->content_view = $view;
    }

    /**
     * 	@author: 		Marco Dennstädt
     * 	@ToDo: 			Store navigation in DB? & Userspecific navigation
     * 	@return: 		array
     * 	This function creates the navigation Array which will be shown on the page. This happens hardcoded		
     */
    private function create_navigation() {
        $teamroles = $this->employee->teamrole();
        $active_teamrole = $teamroles[$this->active_team];

        $items = Model\Roletype::find($active_teamrole->roletype_id)->navitem();

        $list = array();
        foreach ($items as $item) {
            $list[] = anchor($item->controller . '/' . $item->function, $item->name);
        }

        return $list;
    }

    private function _temp_navigation() {
        $list = array(anchor('/', 'Startseite'),
            anchor('/catalogue', 'Schulungskatalog') => array(anchor('/', 'Neue Schulung')),
            anchor('/', 'InHouse Schulungen') => array(anchor('/', 'Neue InHouse Schulung'), anchor('/', 'Vergangene InHouse Schulungen')),
            anchor('/team', 'Mein Team') => array(anchor('/', 'Personalübersicht')),
            anchor('/', 'Reports'),
            anchor('/', 'Grunddaten') => array(anchor('/', 'Benutzer'), anchor('/', 'Mitarbeiter'), anchor('/', 'Teams'), anchor('/', 'Fachbereiche'), anchor('/', 'Fachthemen')),
            anchor('/import/', 'Import'),
            anchor('/data_management', 'Verwaltung') => array(anchor('/data_management/create_measure', 'Maßnahme erstellen')),
            anchor('/user/', 'Persönliche Einstellungen') => array(anchor('/', 'Signatur ändern')));
    }

    public function _output($output) {
        if ($this->tank_auth->is_logged_in()) {
            $data['username']   = $this->tank_auth->get_email();
            $data['headline']   = $this->headline;
            $data['navigation'] = $this->create_navigation();

            if ($this->show_sidebar) {
                $data['show_sidebar'] = $this->show_sidebar;
                $calSettings = array('start_day' => 'monday', 'show_next_prev' => 'TRUE');
                $calSettings['template'] = '{week_day_cell}<td class="wdc">{week_day}</td>{/week_day_cell}
                                            {cal_cell_no_content_today}<div class="highlight">{day}</div>{/cal_cell_no_content_today}
                                            {heading_previous_cell}<th><a href="'.base_url().'index.php/calendar/load/{previous_url}" id="prevMonth">&lt;&lt;</a></th>{/heading_previous_cell}
                                            {heading_next_cell}<th><a href="'.base_url().'index.php/calendar/load/{next_url}" id="nextMonth">&gt;&gt;</a></th>{/heading_next_cell}';
                // Set Cal Language to 'German'
                $this->lang->load('calendar', 'deutsch');
                $this->load->library('calendar', $calSettings);
            }
            //default content view
        }

        if (FALSE !== $this->content_view && empty($this->content_view)) {
            $this->content_view = $this->router->class . '/' . $this->router->method;
        }


        //render the content view
        $data['yield'] = FALSE;

        if (file_exists(APPPATH . 'views/' . $this->content_view . EXT)) {
            $data['yield'] = $this->load->view($this->content_view, $this->view_data, TRUE);
        } else {
            $data['headline']   = 'Error';
            $data['yield']      = 'Content View `' . $this->content_view . '` not found!';
        }

        $this->benchmark->mark('bench_end');
        if ($time = $this->session->flashdata('benchmark')) {
            $time += $this->benchmark->elapsed_time('bench_start', 'bench_end');
        } else {
            $time = $this->benchmark->elapsed_time('bench_start', 'bench_end');
        }

        $data['benchmark'] = $time;
        if ($this->layout_view) {
            $trainingstatus_schwebend   = Model\Trainingstatus::with('id')->find_by_name('Schwebend');
            $objekte_schwebend          = Model\Training::find_by_trainingstatus_id($trainingstatus_schwebend[0]->id);

            $trainingstatus_festgelegt  = Model\Trainingstatus::with('id')->find_by_name('Festgelegt');
            $objekte_festgelegt         = Model\Training::find_by_trainingstatus_id($trainingstatus_festgelegt[0]->id);

            $trainingstatus_gebucht     = Model\Trainingstatus::with('id')->find_by_name('Gebucht');
            $objekte_gebucht            = Model\Training::find_by_trainingstatus_id($trainingstatus_gebucht[0]->id);
            
            $trainingstatus_fakturiert  = Model\Trainingstatus::with('id')->find_by_name('Fakturiert');
            $objekte_fakturiert         = Model\Training::find_by_trainingstatus_id($trainingstatus_fakturiert[0]->id);
            
            $data['sidebardata']        = array('approaching_trainings'    => $objekte_schwebend,
                                                'determined_trainings'     => $objekte_festgelegt,
                                                'entered_trainings'        => $objekte_gebucht,
                                                'invoiced_trainings'       => $objekte_fakturiert);
                                    
            
            echo $this->load->view($this->layout_view, $data, TRUE);
        } else {
            echo $data['yield'];
        }
    }

    /**
     * Displays an Error Message
     * 
     * @param string $headline
     * @param string $message
     * @param string $grade - for example: success,info. By default: error
     */
    public function display_error($headline = FALSE, $message, $grade = FALSE) {
        if ($headline) {
            $this->headline = $headline;
        }
        $this->view_data['message']     = $message;
        if ($grade)
            $this->view_data['grade']   = $grade;
        else
            $this->view_data['grade']   = 'error';

        $this->set_content_view('error');
    }

}

